package moniter

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

var remoteAddr_ string

//重新设置时间间隔
func HttpSetTime(w http.ResponseWriter, r *http.Request) {

	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println("Read failed:", err)
	}
	defer r.Body.Close()

	fmt.Println("http Post:", data, string(data))

	s := strings.Split(string(data), "=")
	timeInterval, _ := strconv.Atoi(s[1])
	if timeInterval == 0 {
		fmt.Println("Read timeInterval:", timeInterval)
		w.Write([]byte("timeInterval is 0,fail"))
		return
	}
	SetTimeInterval(timeInterval)

	w.Write([]byte("OK"))
	//	fmt.Println("http Post SetTime", setTime)

}

func SetTimeInterval(val int) {
	timeInterval = val
}

//上报本地的总数据到远端
func ReportToHttp() {

	data, err := json.Marshal(NameToInfo)
	if err != nil {
		fmt.Println("json Marshal err:", err.Error())
		return
	}

	url := fmt.Sprintf("http://%s/Report", remoteAddr_)
	contentType := "application/json;charset=utf-8"

	body := bytes.NewBuffer(data)

	_, err = http.Post(url, contentType, body)
	if err != nil {
		//fmt.Println("Report failed:", err)
		return
	}
}

func HttpStart(localAddr, remoteAddr string) {
	fmt.Println("Http Server start On :", localAddr)
	fmt.Println("Send data To RemoteAddr :", remoteAddr)
	remoteAddr_ = remoteAddr

	http.HandleFunc("/SetTime", HttpSetTime)

	err := http.ListenAndServe(localAddr, nil)
	if err != nil {
		fmt.Println("dir http err:", err)
	}
}
